#!/usr/bin/python2.6

import MySQLdb
import sys, re
from cmd import getbldlst
from conf import BUILD_LIST

SHIPPED_RELEASE_BUILDS = {'s11': '175b',
                          's11u1': '24b',
                         }

def gen_bldlst():
    con = MySQLdb.connect(host='localhost',
                         user='woxadm',
                         passwd='lz3ssb',
                         db='wox')
    with con:
        cur = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)   
    
        cur.execute('SELECT id, name, host_eg, domain FROM wox_site')       
        sites = cur.fetchall()
       
        cur.execute('SELECT name, description FROM wox_osrelease')      
        oses = cur.fetchall()

        # [site_id:site_name]
        # <os_release>:<os_rel desc.>:<place_holder>:<build no. list>
        # <os_release>:<os_rel desc.>:<place_holder>:<build no. list>
        # ...
        # [site_id:site_name]
        # <os_release>:<os_rel desc.>:<place_holder>:<build no. list>
        # ...
        regexp = re.compile(r'(^.*Builds are\s+)([\S].*$)')
        bldlst_content = ''
        for site in sites:
            bldlst_content += "[%d:%s]\n" % (site['id'], site['name'])
            for os in oses:
                (retval, stdout) = getbldlst(site['host_eg'], 
                                             site['domain'], 
                                             os['name'])[:2:]
                if retval == 1:
                    if os['name'] in SHIPPED_RELEASE_BUILDS:
                        bldlst_content += "%s:%s::%s\n" % (os['name'], 
                                                           os['description'], 
                                                           SHIPPED_RELEASE_BUILDS[os['name']])
                    else:      
                        for l in stdout.splitlines():
                            match = regexp.search(l)
                            if match:
                                bldlst_content += "%s:%s::%s\n" % (os['name'], 
                                                                   os['description'], 
                                                                   match.group(2))
                                break
    
    with open(BUILD_LIST, 'w') as blf:
        blf.write(bldlst_content)


if __name__ == '__main__':
    gen_bldlst()
